package com.lin.msmservice.controller;

import com.lin.commonutils.R;
import com.lin.msmservice.utils.RandomUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{email}")
    public R sendMail(@PathVariable String email){
        //1.从redis获取验证码，如果获取到就直接返回
        String code = redisTemplate.opsForValue().get(email);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        // 2.如果获取不到，则通过邮箱进行发送
        // 生成随机值，传递给邮箱进行发送
        code = RandomUtil.getFourBitRandom();
//        Map<String,Object> param = new HashMap<>();
//        param.put("code",code);
//        SimpleMailMessage message = new SimpleMailMessage();
//        message.setFrom("1754662347@qq.com");
//        message.setTo(email);
//        message.setSubject("it is a test for spring boot");
//        message.setText("你好，我是小lin，我正在测试发送邮件。验证码是:"+param.get(code));
//        try {
//            mailSender.send(message);
//            logger.info("小黄的测试邮件已发送。");
//            // 发送成功，把发送成功的验证码放到redis里面
//            // 设置有效时间
        redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);
        return R.ok();
//        } catch (Exception e) {
//            logger.error("小黄发送邮件时发生异常了！", e);
//            return R.error().message("邮箱发送失败");
//        }
    }
}
